package com.yixun.qfbao.api.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.yixun.qfbao.api.service.CompanyService;
import com.yixun.qfbao.api.service.MyService;
import com.yixun.qfbao.api.service.WeiXinService;
import com.yixun.qfbao.constant.WxConstant;
import com.yixun.qfbao.mapper.DepartmentMapper;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.Department;
import com.yixun.qfbao.model.dto.CompanyDto;
import com.yixun.qfbao.model.enums.SystemIdEnum;
import com.yixun.qfbao.service.GetWeAppQrCodeService;
import com.yixun.qfbao.service.PartnerInfoService;
import com.yixun.qfbao.util.QiNiuUtil;
import com.yixun.qfbao.util.SpringContextUtil;
import com.yixun.qfbao.util.StringUtil;
import com.yixun.qfbao.util.WxAccessTokenCacheUtils;

/**
 * @author zilong.liu
 * @date 2020-11-19
 *
 * desc:
 *     
 */
@Service
public class MyServiceImpl implements MyService {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(MyServiceImpl.class);
	
	@Autowired
	PartnerInfoService partnerInfoService;
	
	@Autowired
	CompanyService companyService;
	
	@Autowired
	DepartmentMapper departmentMapper;
	
	@Lazy
	@Autowired
	WeiXinService weiXinService;
	
	@Autowired
	WxAccessTokenCacheUtils wxAccessTokenCacheUtils;

	@Override
	public void loginExit(String systemId, String companyUuid, String userId) {
		if(!StringUtils.isEmpty(userId) && enableWeappMsg(systemId, companyUuid)) {
			partnerInfoService.clearOpenidByUserId(Long.parseLong(userId));
		}
	}
	
	/**
	 * 判断当前公司是否开启了分销小程序
	 * @return
	 * 
	 */
	@Override
	public boolean enableWeappMsg(String systemId, String companyUuid) {
		if(!SystemIdEnum.WEAPP_AGENCY.getCode().equals(systemId)) {
			return true;
		}
		CompanyDto companyDto = new CompanyDto();
		companyDto.setCompanyUuid(companyUuid);
		Company company = companyService.selectByDto(companyDto);
		String enableWeappMsg = company.getEnableWeappMsg();
		if("1".equals(enableWeappMsg)) {
			return true;
		}
		return false;
	}

	/**
	 * 根据传入的底层ID， 获取当前部门对应的二维码连接
	 * @param id  由此会传入实现了GetWeAppQrCodeService接口的方法中
	 * @param strategy 对应的实现了GetWeAppQrCodeService接口的bean名称，后续可以传递参数进入各内部具体实现，避免一个dao多个策略
	 * @return
	 */
	@Override
	public String getQrCodeUrl(String userId, Long id, String companyUuid, String... strategy) {
		if(!StringUtil.isNotNull(userId)) {
			return "失败: userId未传入";
		}

		if(!StringUtil.isNotNull(companyUuid)) {
			return "失败: companyUuid未传入";
		}
		
		// 1、判断当前公司是否启用了小程序
		if(!enableWeappMsg(SystemIdEnum.WEAPP_AGENCY.getCode(), companyUuid)) {
			LOGGER.info("MyServiceImpl->getDepartmentQrCodeUrl->,此公司未开启分销小程序功能: {}", companyUuid);
			return "失败: 此公司未开启分销小程序功能";
		}
		
		// 2、从数据库获取对应的链接信息
		GetWeAppQrCodeService getWeAppQrCodeDao = SpringContextUtil.getBean(strategy[0]);
		String qrCodeUrl = getWeAppQrCodeDao.getWeAppQrCodeUrl(userId, id, strategy);
		if(StringUtil.isNotNull(qrCodeUrl)) {
			return qrCodeUrl;
		}
		
		// 3、生成需要携带的参数
		String scene = getWeAppQrCodeDao.getWeAppScene(userId, id, companyUuid, strategy);
		
		String page = getWeAppQrCodeDao.getPage(strategy[0]);
		
		// 4、如果未包含，则生成二维码并上传
		byte[] weappQrCode = weiXinService.getWeappQrCodeByCompanyUuid(companyUuid, 
				String.valueOf(scene), page);
		try {
			String result = new String(weappQrCode, "UTF-8");
			if(result.indexOf("40001") > -1) {
				wxAccessTokenCacheUtils.remove(companyUuid, SystemIdEnum.WEAPP_AGENCY.getCode());
				weappQrCode = weiXinService.getWeappQrCodeByCompanyUuid(companyUuid, 
						String.valueOf(scene), page);
			}else if(result.contains("errcode")) {
				LOGGER.error("MyServiceImpl->getQrCodeUrl->生成二维码链接失败，失败信息为:{}", result);
				weappQrCode = null;
			}
		} catch (UnsupportedEncodingException e1) {
			LOGGER.error(e1.getMessage(), e1);
		}
		
		//包含errorCode，则直接返回错误信息，生成失败，稍后再试
		if(weappQrCode == null) {
			return "失败: 小程序二维码生成失败，请稍后再试";
		}
		// 5、将生成的二维码上传至七牛
		String fileUrl = "";
		try {
			fileUrl = QiNiuUtil.upload(weappQrCode, ".png");
		} catch (IOException e) {
			LOGGER.error(e.getMessage(), e);
		}
		if(StringUtils.isEmpty(fileUrl)) {
			return "失败：图片上传至七牛云失败，请稍后再试";
		}
		
		// 6、保存上传之后的七牛链接
		getWeAppQrCodeDao.saveQrCodeUrl(userId, id, fileUrl, strategy);
		return fileUrl;
	}
	
	/**
	 *	 构建部门的分销小程序二维码对应的参数
	 * @param companyUuid
	 * @param deptId
	 * @return
	 */
	@Override
	public String getRegesiterDeptInfo(long deptId) {
		Department department = departmentMapper.selectById(deptId);
		if(department == null) {
			LOGGER.info("MyServiceImpl->getDeptWeappQrCodeScene:{},当前deptId无对应的公司", deptId);
			return null;
		}
		String permissionCode = department.getPermissionCode();
		Long agentCompanyId = department.getMerchantId();
		int index = permissionCode.indexOf("-");
		if(index <= -1) {
			return String.valueOf(agentCompanyId);
		}
		permissionCode = agentCompanyId + permissionCode.substring(index);
		permissionCode = permissionCode.replaceAll("-", "|");
		return permissionCode;
	}
	
}
